import re

from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User
from utils.utils import generate_check_token


class OauthQQUserAPIViewSerialzier(serializers.Serializer):

    mobile = serializers.CharField(required=True,min_length=11,max_length=11,label='手机号')
    sms_code = serializers.CharField(required=True,min_length=6,max_length=6,label='验证码')
    password = serializers.CharField(required=True,min_length=8,max_length=20,label='密码')
    access_token = serializers.CharField()

    def validate(self, attrs):
        mobile = attrs.get('mobile')

        if not re.match(r'1[3-9]\d{9}',mobile):
            raise serializers.ValidationError('手机号格式错误')

        openid = attrs.get('access_token')

        openid = generate_check_token(openid)

        if openid is None:
            raise serializers.ValidationError('绑定失效过期')

        self.openid = openid

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')

        try:
            redis_text = redis_conn.get('sms_%s'%mobile)

        except Exception:
            raise serializers.ValidationError('短信验证码过期')

        sms_code = attrs.get('sms_code')
        if redis_text.decode() != sms_code:
            raise serializers.ValidationError('短信验证码输入有误')

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNOtExist:
            pass

        else:
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码不正确')

            self.user = user

        return attrs

    def create(self, validated_data):
        user = self.user
        openid = self.openid

        if user is None:

            user = User.objects.create(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')

            )
        user.set_password(validated_data.get('password'))
        user.save()

        qquser = OAuthQQUser.objects.create(
            user= user,
            openid = openid
        )

        return qquser
